package com.sgcc.ln.pmos.mobileapp.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgcc.ln.pmos.arouter.app.AppArouterPath;
import com.sgcc.ln.pmos.common.base.MvpBaseActivity;
import com.sgcc.ln.pmos.common.bean.EventCenter;
import com.sgcc.ln.pmos.common.bean.UploadData;
import com.sgcc.ln.pmos.common.bean.UploadDataBean;
import com.sgcc.ln.pmos.common.http.DownloadUtil;
import com.sgcc.ln.pmos.common.http.HttpInterConst;
import com.sgcc.ln.pmos.common.http.HttpRequestUtils;
import com.sgcc.ln.pmos.common.http.MvcNetCallback;
import com.sgcc.ln.pmos.common.http.UploadUtil;
import com.sgcc.ln.pmos.common.utils.ArguConstant;
import com.sgcc.ln.pmos.common.utils.ImmersionBarUtils;
import com.sgcc.ln.pmos.common.utils.XXPermissionsUtil;
import com.sgcc.ln.pmos.common.utils.picture.PictureSelectUtil;
import com.sgcc.ln.pmos.common.widget.MyEditText;
import com.sgcc.ln.pmos.common.widget.TitleBar;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.ln.pmos.mobileapp.bean.DoLoginReleaseBean;
import com.sgcc.ln.pmos.mobileapp.bean.LinkmanInfoBean;
import com.sgcc.ln.pmos.mobileapp.bean.StatusBean;
import com.sgcc.ln.pmos.mobileapp.contract.AddOrEditContactContract;
import com.sgcc.ln.pmos.mobileapp.presenter.AddOrEditContactPresenter;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 新增 / 编辑联系人
 */
@Route(path = AppArouterPath.APP_ADDOREDITCONTACT)
public class AddOrEditContactActivity extends MvpBaseActivity<AddOrEditContactPresenter> implements AddOrEditContactContract.View {

    private TitleBar mTitleBar;
    private Switch mSwitchFitstcontact;
    private LinearLayout mLlFileTitle;
    private RelativeLayout mLlFile;
    private RelativeLayout mRlClose;
    private TextView mTvFile;
    private LinearLayout mLlBtnFile;
    private RelativeLayout mRlLocalFile;
    private RelativeLayout mRlShootPhotoAlbum;
    private TextView mTvFiledownload;
    private MyEditText mEtName;
    private LinearLayout mLlIdCard;
    private MyEditText mEtIdCard;
    private MyEditText mEtPhone;
    private MyEditText mEtMachineno;
    private MyEditText mEtEmail;
    private CheckBox mCb1;
    private CheckBox mCb2;
    private CheckBox mCb3;
    private CheckBox mCb4;
    private MyEditText mEtNote;
    private TextView mTvPrompt;
    private RelativeLayout mRlStartRealnameauth;
    private TextView mTvBtnText;
    private LinkmanInfoBean.DataBean mBean;
    private String fileName, filePath, fileSize;
    private UploadData mUploadDataBean;
    private int isCommomContact;

    @Autowired
    public boolean isHasCommomContact = false;//前面页面是否有第一联系人

    private boolean isEditNameOrIdCard = false;//是否更改了身份证或者姓名
    // true更改过之后需要重新实名认证，false否者只需要保存数据

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_customcenter_contact;
    }

    @Override
    protected AddOrEditContactPresenter createPresenter() {
        return new AddOrEditContactPresenter();
    }

    @Override
    protected void initViews() {
        super.initViews();
        ImmersionBarUtils.initTrans1lBar(this);
        mBean = (LinkmanInfoBean.DataBean) getIntent().getSerializableExtra("LinkmanInfoBean");

        findViewByIds();
        setViewAction();

        if (mBean != null) {
            mSwitchFitstcontact.setChecked("1".equals(mBean.getIsCommomContact()) ? true : false);
            mEtName.setText(mBean.getContactName());
            mEtIdCard.setText(mBean.getDoucumentNumber());
            mEtPhone.setText(mBean.getTelephone());
            mEtIdCard.setText(mBean.getDoucumentNumber());
            mEtMachineno.setText(mBean.getOfficePhone());
            mEtEmail.setText(mBean.getEmail());
            mEtNote.setText(mBean.getRemarks());
            List<UploadData> mmMembersAffixRegs = mBean.getMmMembersAffixRegs();

            if (null != mmMembersAffixRegs && mmMembersAffixRegs.size() > 0) {
                mUploadDataBean = mmMembersAffixRegs.get(0);
                mTvFile.setText("授权文件." + getExtensionName(mUploadDataBean.getAffixName()));
                mLlFile.setVisibility(View.VISIBLE);
                mLlBtnFile.setVisibility(View.GONE);
            }

            String contactTypes[] = mBean.getContactType().split(",");
            if (null != contactTypes && contactTypes.length > 0) {
                mCb1.setChecked(false);
                mCb2.setChecked(false);
                mCb3.setChecked(false);
                mCb4.setChecked(false);

                for (int i = 0; i < contactTypes.length; i++) {
                    if ("1".equals(contactTypes[i])) {
                        mCb1.setChecked(true);
                    }
                    if ("2".equals(contactTypes[i])) {
                        mCb2.setChecked(true);
                    }
                    if ("5".equals(contactTypes[i])) {
                        mCb3.setChecked(true);
                    }
                    if ("6".equals(contactTypes[i])) {
                        mCb4.setChecked(true);
                    }
                }
            }

            mEtName.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    if (mSwitchFitstcontact.isChecked()) {
                        isEditNameOrIdCard = !editable.toString().equals(mBean.getContactName());
                        setTvBtnText();
                    }

                }
            });
            mEtIdCard.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    if (mSwitchFitstcontact.isChecked()) {
                        isEditNameOrIdCard = !editable.toString().equals(mBean.getDoucumentNumber());
                        setTvBtnText();
                    }


                }
            });
        } else {
            if (!isHasCommomContact) {
                isEditNameOrIdCard = true;
            }
        }
    }

    private void setTvBtnText() {
        mTvBtnText.setText(isEditNameOrIdCard ? "开始人脸识别" : "保存");
    }

    private void setViewAction() {
        mRlLocalFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance()
                        .build(AppArouterPath.APP_CHOOSEFILE)
                        .navigation(AddOrEditContactActivity.this, 1111);
            }
        });

        mRlShootPhotoAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                XXPermissionsUtil.camera(AddOrEditContactActivity.this, new XXPermissionsUtil.PermissionCallback() {
                    @Override
                    public void Call() {
                        PictureSelectUtil.select(AddOrEditContactActivity.this, true, 0x21, null);
                    }
                });
            }
        });

        mSwitchFitstcontact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                changelayout();
            }
        });

        mTvFiledownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DownloadUtil.get().downloadPdf2(ActivityUtils.getTopActivity(), HttpInterConst.DOWNCONFIGFILE, new DownloadUtil.OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(File file) {
                        ToastUtils.showShort("文件下载成功 目录：" + file.getAbsolutePath());
                    }

                    @Override
                    public void onDownloading(int progress) {

                    }

                    @Override
                    public void onDownloadFailed(Exception e) {

                    }
                });
            }
        });

        mRlClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fileName = null;
                if (TextUtils.isEmpty(fileName)) {
                    mLlFile.setVisibility(View.GONE);
                    mLlBtnFile.setVisibility(View.VISIBLE);
                } else {
                    mLlFile.setVisibility(View.VISIBLE);
                    mLlBtnFile.setVisibility(View.GONE);
                }
            }
        });

        mRlStartRealnameauth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                isCommomContact = mSwitchFitstcontact.isChecked() ? 1 : 0;
                if (isCommomContact == 1) {
                    if (mUploadDataBean == null) {
                        ToastUtils.showShort("请选择授权文件");
                        return;
                    }
                }

                String contactName = mEtName.getText().toString().trim();
                if (TextUtils.isEmpty(contactName)) {
                    ToastUtils.showShort("请输入联系人姓名");
                    return;
                }
                if (!RegexUtils.isZh(contactName)) {
                    ToastUtils.showShort("联系人姓名必须为汉字");
                    return;
                }
                String IdCard = null;
                if (isCommomContact == 1) {
                    IdCard = mEtIdCard.getText().toString().trim();
                    if (TextUtils.isEmpty(IdCard)) {
                        ToastUtils.showShort("请输入身份证号");
                        return;
                    }
                }

                String telephone = mEtPhone.getText().toString().trim();
                if (TextUtils.isEmpty(telephone)) {
                    ToastUtils.showShort("请输入联系电话");
                    return;
                }

                if (!RegexUtils.isMobileExact(telephone)) {
                    ToastUtils.showShort("请输入正确的联系电话");
                    return;
                }

                String officePhone = mEtMachineno.getText().toString().trim();

                String email = mEtEmail.getText().toString().trim();
                if (TextUtils.isEmpty(email)) {
                    ToastUtils.showShort("请输入邮箱");
                    return;
                }

                if (mCb1.isChecked() == false && mCb2.isChecked() == false && mCb3.isChecked() == false && mCb4.isChecked() == false) {
                    ToastUtils.showShort("请选择专业");
                    return;
                }

                StringBuffer sb = new StringBuffer();
                if (mCb1.isChecked()) {
                    sb.append("1,");
                }
                if (mCb2.isChecked()) {
                    sb.append("2,");
                }
                if (mCb3.isChecked()) {
                    sb.append("5,");
                }
                if (mCb4.isChecked()) {
                    sb.append("6,");
                }

                String remarks = mEtNote.getText().toString().trim();
                String guid = null;
                if (mBean != null) {
                    guid = mBean.getGuid();
                }

                String fileId = null;
                if (mUploadDataBean != null) {
                    fileId = mUploadDataBean.getFileId();
                }

                String contactType = sb.substring(0, sb.toString().length() - 1);

                if (mSwitchFitstcontact.isChecked()) {
                    if (isEditNameOrIdCard)
                        queryForBound(fileId, contactName, IdCard, telephone,
                                officePhone, email, contactType, remarks, guid);
                    else {
                        saveLinkmanInfo(contactName, IdCard, contactType, email,
                                isCommomContact, fileId,
                                officePhone, remarks, telephone, guid);
                    }
                } else {
                    saveLinkmanInfo(contactName, "", contactType, email,
                            isCommomContact, fileId,
                            officePhone, remarks, telephone, guid);
                }
            }
        });
    }


    private void queryForBound(String fileId, String contactName, String IdCard, String telephone,
                               String officePhone, String email, String contactType, String remarks, String guid) {
        Map<String, Object> params = new HashMap<>();
        params.put("auth_id", IdCard);
        params.put("auth_people", contactName);
        HttpRequestUtils.getInstance().request(params,
                HttpInterConst.QUERY_FOR_BOUND, new MvcNetCallback<StatusBean>(true) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        super.onError(call, e, id);
                        // 失败回调 判断界面是否销毁
                    }

                    @Override
                    public void onResponse(StatusBean response, int id) {
                        super.onResponse(response, id);
                        if (response != null && response.getStatus() == 0) {
                            ARouter.getInstance()
                                    .build(AppArouterPath.APP_VIDEOATTESTATIONACTIVITY)
                                    .withString("fileId", fileId)
                                    .withString("realName", contactName)
                                    .withString("idCordNumber", IdCard)
                                    .withString("telephone", telephone)
                                    .withString("officePhone", officePhone)
                                    .withString("email", email)
                                    .withString("contactType", contactType)
                                    .withString("remarks", remarks)
                                    .withInt("isCommomContact", 1)
                                    .withString("guid", guid)
                                    .navigation();
                        } else {
                            ToastUtils.showShort(response.getMessage());
                        }
                    }
                });


    }


    private void findViewByIds() {
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mSwitchFitstcontact = (Switch) findViewById(R.id.switch_fitstcontact);
        mLlFileTitle = (LinearLayout) findViewById(R.id.ll_file_title);
        mLlFile = (RelativeLayout) findViewById(R.id.ll_file);
        mRlClose = (RelativeLayout) findViewById(R.id.rl_close);
        mTvFile = (TextView) findViewById(R.id.tv_file);
        mLlBtnFile = (LinearLayout) findViewById(R.id.ll_btn_file);
        mRlLocalFile = (RelativeLayout) findViewById(R.id.rl_local_file);
        mRlShootPhotoAlbum = (RelativeLayout) findViewById(R.id.rl_shoot_photo_album);
        mTvFiledownload = (TextView) findViewById(R.id.tv_filedownload);
        mEtName = (MyEditText) findViewById(R.id.et_name);
        mLlIdCard = (LinearLayout) findViewById(R.id.ll_idCard);
        mEtIdCard = (MyEditText) findViewById(R.id.et_idCard);
        mEtPhone = (MyEditText) findViewById(R.id.et_phone);
        mEtMachineno = (MyEditText) findViewById(R.id.et_Machineno);
        mEtEmail = (MyEditText) findViewById(R.id.et_email);
        mCb1 = (CheckBox) findViewById(R.id.cb_1);
        mCb2 = (CheckBox) findViewById(R.id.cb_2);
        mCb3 = (CheckBox) findViewById(R.id.cb_3);
        mCb4 = (CheckBox) findViewById(R.id.cb_4);
        mEtNote = (MyEditText) findViewById(R.id.et_note);
        mTvPrompt = (TextView) findViewById(R.id.tv_prompt);
        mRlStartRealnameauth = (RelativeLayout) findViewById(R.id.rl_start_realnameauth);
        mTvBtnText = (TextView) findViewById(R.id.tv_btn_text);
        TextView tvHintText = (TextView) findViewById(R.id.tvHintText);

        mTitleBar.setTitle("新增/编辑联系人");
        mTitleBar.setRightIcon(R.mipmap.go_main, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goMainActivity();
            }
        });
        if (mBean != null) {
            isCommomContact = mBean.getIsCommomContact().equals("1") ? 1 : 0;
            mSwitchFitstcontact.setChecked(isCommomContact == 1);
            if (isCommomContact == 0 && isHasCommomContact) {
                tvHintText.setText("已存在第一联系人，无法再增加第一联系人");
                mSwitchFitstcontact.setChecked(false);
                mSwitchFitstcontact.setEnabled(false);
            }

        } else {
            if (isHasCommomContact) {
                isCommomContact = 0;
                tvHintText.setText("已存在第一联系人，无法再增加第一联系人");
                mSwitchFitstcontact.setChecked(false);
                mSwitchFitstcontact.setEnabled(false);
            }
        }
        changelayout();
    }

    private void changelayout() {
        if (mSwitchFitstcontact.isChecked()) {

            mTvFiledownload.setVisibility(View.VISIBLE);
            mLlFileTitle.setVisibility(View.VISIBLE);
            mLlBtnFile.setVisibility(View.VISIBLE);
//            mTvPrompt.setVisibility(View.VISIBLE);
            mLlIdCard.setVisibility(View.VISIBLE);

            if (TextUtils.isEmpty(fileName)) {
                mLlFile.setVisibility(View.GONE);
                mLlBtnFile.setVisibility(View.VISIBLE);
            } else {
                mLlFile.setVisibility(View.VISIBLE);
                mLlBtnFile.setVisibility(View.GONE);
            }
            if (!isHasCommomContact)
                isEditNameOrIdCard = true;
            setTvBtnText();
        } else {
            mLlFile.setVisibility(View.GONE);
            mTvFiledownload.setVisibility(View.GONE);
            mLlFileTitle.setVisibility(View.GONE);
            mLlBtnFile.setVisibility(View.GONE);
//            mTvPrompt.setVisibility(View.GONE);
            mLlIdCard.setVisibility(View.GONE);
            mTvBtnText.setText("保存");
        }
    }

    public void saveLinkmanInfo(String contactName, String doucumentNumber, String contactType, String email, int isCommomContact, String fileId, String officePhone, String remarks, String telephone, String guid) {
        Map<String, Object> params = new HashMap<>();
        params.put("contactName", contactName);
        if (!TextUtils.isEmpty(doucumentNumber))
            params.put("doucumentNumber", doucumentNumber);
        params.put("contactType", contactType);
        params.put("email", email);
        params.put("isCommomContact", isCommomContact);
        params.put("officePhone", officePhone);
        params.put("remarks", remarks);
        params.put("telephone", telephone);
        params.put("guid", guid);
        params.put("fileId", fileId);

//        params.put("contactTypeList", contactType.split(","));

        HttpRequestUtils.getInstance().request(params, HttpInterConst.SAVELINKMANINFO, new MvcNetCallback<DoLoginReleaseBean>(true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
            }

            @Override
            public void onResponse(DoLoginReleaseBean response, int id) {
                super.onResponse(response, id);
                if (response != null) {
                    if (response.getStatus() == 0 && "Success".equals(response.getMessage())) {
                        EventBus.getDefault().post(new EventCenter<>(ArguConstant.SAVE_CONTACT_BACK));
                        finish();
                    }
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2222) {
            if (requestCode == 1111) {
                fileName = data.getStringExtra("FileName");
                filePath = data.getStringExtra("FilePath");
                fileSize = data.getStringExtra("FileSize");
                mTvFile.setText("授权文件." + getExtensionName(fileName));
                mLlFile.setVisibility(View.VISIBLE);
                mLlBtnFile.setVisibility(View.GONE);
                upLoadFile();
            }
        }
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 0x21) {
                ArrayList<LocalMedia> localMediaList = PictureSelector.obtainSelectorList(data);
                if (null != localMediaList && localMediaList.size() > 0) {
                    LocalMedia localMedia = localMediaList.get(0);
                    fileName = localMedia.getFileName();
                    filePath = PictureSelectUtil.getPath(localMedia);
                    mTvFile.setText("授权文件." + getExtensionName(fileName));
                    mLlFile.setVisibility(View.VISIBLE);
                    mLlBtnFile.setVisibility(View.GONE);
                    upLoadFile();
                }
            }
        }
    }

    public void upLoadFile() {
        UploadUtil.upload("", "604", fileName, "", fileName, new File(filePath), new MvcNetCallback<UploadDataBean>(true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
            }

            @Override
            public void onResponse(UploadDataBean response, int id) {
                super.onResponse(response, id);
                if (null != response && null != response.getData() && response.getData().size() > 0) {
                    mUploadDataBean = response.getData().get(0);
                }
            }
        });
    }

    /**
     * 文件操作 获取文件扩展名
     *
     * @param filename
     * @return
     */
    public String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }
}
